import { defineStore } from 'pinia'
import router from '@/router'
import { usePermissionStore } from './permission'
import { getUserPermission } from '@/api/user'

function listFormat(arr) {
  arr.forEach(el => {
    const showInd = window.Glob.FilterMenu.findIndex(item => item === el.path)
    const mainMenuIsShow = showInd === -1 ? false : true
    el.meta = { ...el.meta, mainMenuIsShow }
    if (el.children && el.children.length > 0) {
      el.children = listFormat(el.children)
    }
  })
  return arr
}

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null,
    permission: localStorage.permission ? JSON.parse(localStorage.permission) : [],
    menuItemList: []
  }),
  actions: {
    logout(){
      localStorage.clear()
      const permissionStore = usePermissionStore()
      permissionStore.isHandle = false
      router.push('/login')
    },
    // 存储用户信息
    async setUserInfo (data) {
      console.log('用户信息----------->', data)
      this.userInfo = data
      localStorage.userInfo = JSON.stringify(data)
      getUserPermission().then(({ result }) => {
        this.permission = listFormat(result)
        this.permission = [ ...result ]
        localStorage.permission = JSON.stringify([ ...result ])
        console.log('用户信息AAAAAA----------->', result)
        console.log('用户信息BBBBBB----------->',  localStorage.permission)
      })
      setTimeout(() => {
        this.getMenuList()
        router.push('/')
      }, 700)
    },
    // 获取左侧菜单栏
    getMenuList() {
      const hederMenuList:any = localStorage.permission
      const menuArr:any = []
      for (const i in hederMenuList) {
        menuArr.push(hederMenuList[i])
      }
      console.log('左侧菜单栏----->', hederMenuList)
      // 获取斗轮机编号
      if (menuArr.length > 0) {
        const barCoder = menuArr[0].path.charAt(menuArr[0].path.length - 1)
        if (Number(barCoder) && menuArr.length) {
          this.menuItemList = hederMenuList
        } else {
          this.menuItemList = menuArr
        }
      } else {
        this.menuItemList = menuArr
      }
      if (menuArr.length > 0) {
        const barCoder = menuArr[0].path.charAt(menuArr[0].path.length - 1)
        if (Number(barCoder) && menuArr.length) {
          this.menuItemList = hederMenuList
        } else {
          this.menuItemList = menuArr
        }
      } else {
        this.menuItemList = menuArr
      }
      
    }
  }
})
